package cn.rubbit.generate;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

import cn.rubbit.ApplicationContext;
import cn.rubbit.entity.Entity;
import cn.rubbit.entity.Project;
import cn.rubbit.entity.Table;
import cn.rubbit.util.GenerateFile;

public class TableGenerate {
	private static Connection conn = (Connection) ApplicationContext.get(ApplicationContext.DB_OBJECT);
	private static Project project = (Project) ApplicationContext.get(ApplicationContext.PJ_OBJECT);
	public static void gernateEntity() {
		List<Table> tables = project.getTables();
		System.out.println("Gernate Bean Code is running");
		List<Table> tableentites = new ArrayList<Table>();
		try {
			if (tables.size() < 1) {
				ResultSet result = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
				while (result.next()) {
					tableentites.add(getTableColumn(result.getString(1) + "." + result.getString(3)));
				}
			} else {
				for (Table tablename : tables) {
					tableentites.add(getTableColumn(tablename.getTable()));
				}
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		for (Table t : tableentites) {
			try {
				generate(t);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
		ApplicationContext.set(ApplicationContext.PJ_TABLES, tableentites);
		System.out.println("Gernate Bean Code is end");
	}

	private static Table getTableColumn(String tableName) {
		String sql = "select * from " + tableName;
		Table table = null;
		try {
			Statement stat = conn.createStatement();
			ResultSet result = stat.executeQuery(sql);
			ResultSetMetaData rsmd = result.getMetaData();
			int columns = rsmd.getColumnCount();
			int i = 1;
			table = new Table();
			table.setPackageName(project.getGroupId() + ".entity");
			table.setTable(tableName.substring(tableName.indexOf('.') + 1));
			List<Entity> entities = new ArrayList<Entity>();
			while (i < columns + 1) {
				Entity entity = new Entity();
				entity.setType(rsmd.getColumnClassName(i));
				entity.setClassName(rsmd.getColumnName(i));
				i++;
				entities.add(entity);
			}
			table.setEntities(entities);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return table;
	}

	private static void generate(Table table) throws InterruptedException {
		if (project == null) {
			throw new InterruptedException("Project is null");
		}
		String path=project.getPath();
		if (!path.endsWith("\\")) {
			path += "\\";
		}
		path += project.getName()+"\\src\\main\\java\\" + (project.getGroupId() + ".entity").replaceAll("\\.", "\\\\");
		GenerateFile.generateFTL(path + "\\" + table.getTable() + ".java", ApplicationContext.ENTITY_FILE, table);
	}

}
